package com.lhs.utils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.lhs.exception.WxException;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;

/**
 * WxUtil
 *
 * @author longhuashen
 * @since 15/12/6
 */
public class WxUtil {

    private static final Logger logger = LoggerFactory.getLogger(WxUtil.class);

    /**
     * 验证签名
     *
     * @param token
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String checkSignature(String token, String signature, String timestamp, String nonce, String echostr) throws WxException {
        logger.info("\nsignature:{},timestamp:{},nonce:{}", signature, timestamp, nonce);

        if (null == signature
                || signature.length() > 128
                || null == timestamp
                || timestamp.length() > 128
                || null == nonce
                || nonce.length() > 128) {
            logger.error("验证签名参数失败!!!");
            logger.error("signature=%s,timestamp=%s,nonce=%s", signature, timestamp, nonce);
            throw new WxException(-90, "signature error");
        }

        if (logger.isDebugEnabled()) {
            logger.info("微信接入URL验证成功...");
            logger.info("signature=%s, timestamp=%s, nonce=%s", signature, timestamp, nonce);
        }

        if (!signature(token, timestamp, nonce).equals(signature)) {
            throw new WxException(-90, "signature error");
        }

        return echostr;
    }

    /**
     * sha1 加密
     *
     * @param args
     * @return
     */
    public static String signature(String... args) {
        Preconditions.checkNotNull(args);
        return DigestUtils.shaHex(dicSort(args));
    }

    /**
     * 字典排序
     *
     * @param strings 需要排序的字符串
     * @return 字典排序
     */
    public static String dicSort(String... strings) {
        ArrayList<String> list = Lists.newArrayList(strings);
        Collections.sort(list);

        StringBuilder stringBuffer = new StringBuilder();
        for (String str : list) {
            if (str == null) {
                continue;
            }
            stringBuffer.append(str);
        }
        return stringBuffer.toString();
    }
}
